<template>
  <div class="container">
    <!-- 内容顶部栏 -->
    <div class="content-top">
      <!-- 搜索，添加 -->
      <el-input class="search-input" v-model="searchVal" :placeholder="toggleSearch ? '请输入用户ID' : '请输入用户昵称'"></el-input>
      <!-- <el-tooltip :content="toggleSearch ? '切换为昵称' : '切换为ID'" placement="bottom">
        <el-switch
          v-model="toggleSearch"
          style="--el-switch-on-color: #13ce66; --el-switch-off-color: rgb(19, 122, 206)"
        />
      </el-tooltip> -->
      <el-button v-if="toggleSearch" @click="searchById" icon="Search" round>搜索</el-button>
      <el-button v-else @click="searchByName" icon="Search" round>搜索</el-button>
      <el-button @click="loadUserList" round>清除搜索</el-button>
      <el-button @click="createUser" type="primary" round>创建用户</el-button>
      <div
        style="font-family: 微软雅黑;line-height:25px;margin-left: 500px;height:30px;font-size: 24px;border: 2px solid rgb(64, 158, 255);border-radius:5px;padding: 0px 20px; color: white;background-color: rgb(64, 158, 255);">
        用户管理</div>
    </div>

    <div class="classify">
      <el-button class="classify" type="text" @click="loadUserList">全部</el-button>
      <el-button class="classify" type="text" @click="getAdmin">管理员</el-button>
      <el-button class="classify" type="text" @click="getTeacher">老师</el-button>
      <el-button class="classify" type="text" @click="getJudge">评委</el-button>
      <el-button class="classify" type="text" @click="getAudience">观众</el-button>
    </div>

    <!-- 内容表格开始，border:表格边框 -->
    <el-table :data="userList" border max-height="calc(100vh - 190px)">
      <el-table-column label="序号" type="index" align="center" width="85" />
      <el-table-column label="用户类型" prop="roleId" align="center">
        <template v-slot="scope">
          {{ getRoleLabel(scope.row.roleId) }}
        </template>
      </el-table-column>
      <el-table-column label="头像" prop="profilePath" align="center" width="100">
        <template v-slot="scope">
          <el-image style="width: 60px;height: 60px" fit="cover" :src="scope.row.profilePath" />
        </template>
      </el-table-column>
      <el-table-column label="用户昵称" prop="nickName" align="center" />
      <el-table-column label="用户账号" prop="username" align="center" />
      <el-table-column label="密码  " prop="password" align="center" />
      <el-table-column label="二级学院" prop="academy" align="center" />
      <el-table-column label="联系电话" prop="phone" align="center" />
      <el-table-column label="用户简介(概要)" prop="synopsis" align="center" width="150" />
      <el-table-column label="创建时间" prop="createTime" align="center" />
      <!-- <el-table-column label="更新时间" prop="updateTime" align="center" /> -->
      <el-table-column label="操作" align="center" width="300">
        <template v-slot="scope">
          <el-button @click="editDialog(scope.row)" type="text"><el-icon>
              <Edit />
            </el-icon>编辑</el-button>
          <el-button @click="del(scope.row)" type="text" style="color: red"><el-icon>
              <Delete />
            </el-icon>删除</el-button>
          <el-button @click="resetPassword(scope.row)">重置密码</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div style="padding-left: calc(100% - 650px); text-align: right;margin-top: 10px">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="pageSetting.page_num" :page-sizes="[5, 10, 15, 20]" :page-size="pageSetting.page_size"
        layout="total, sizes, prev, pager, next, jumper" :total="pageSetting.total">
      </el-pagination>
    </div>

    <!-- 弹窗 -->
    <div>
      <el-dialog v-model="dialogVisible" :title="editFormTitle" :visible="dialogVisible" width="40%"
        :before-close="handleBeforeClose">
        <el-form :model="editFormData" :rules="editFormRules" label-position="left" ref="editFormRef">
          <el-form-item label="用户类型" prop="roleId">
            <el-select v-model="editFormData.roleId">
              <el-option v-for="(option, index) in roleIdOptions" :key="index" :label="option.name" :value="option.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="头像路径" prop="profilePath">
            <el-input v-model="editFormData.profilePath" placeholder="请输入头像路径"></el-input>
          </el-form-item>
          <el-form-item label="用户昵称" prop="nickName">
            <el-input v-model="editFormData.nickName" placeholder="请输入用户名"></el-input>
          </el-form-item>
          <el-form-item label="用户账号" prop="username">
            <el-input v-model="editFormData.username" placeholder="请输入用户账号"></el-input>
          </el-form-item>
          <el-form-item label="二级学院" prop="academy">
            <!-- <el-input v-model="editFormData.academy" placeholder="请输入学院名称"></el-input> -->
            <el-select v-model="editFormData.academy" placeholder="选择二级学院">
              <el-option v-for="item in collegeOptions" :key="item.id" :label="item.college" :value="item.college" />
            </el-select>
          </el-form-item>
          <el-form-item label="联系电话" prop="phone">
            <el-input v-model="editFormData.phone" placeholder="请输入联系电话"></el-input>
          </el-form-item>
          <el-form-item label="用户简介(概要)" prop="synopsis">
            <el-input v-model="editFormData.synopsis" placeholder="请输入用户简介(概要)"></el-input>
          </el-form-item>
        </el-form>

        <solt name="footer" style="padding-left: 65%;">
          <el-button @click="handleBeforeClose">取消</el-button>
          <el-button type="primary" @click="handleConfirm">确认</el-button>
        </solt>
      </el-dialog>
    </div>

  </div>
</template>

<script setup>
import {
  GetUserList,
  GetUserById,
  AddUserList,
  DeleteUserList,
  UpdateUserList,
  GetRoleList,
  GetUserByName,
  UpdateUserPassword
} from "@/api/back/user";
import { ref, onMounted } from 'vue';
import { ElMessage, messageConfig, ElMessageBox } from "element-plus";

const toggleSearch = ref(false);
// 分页查询

// ----------分页查询----------
const pageSetting = ref({
  page_num: 1,
  page_size: 10,
  total: 0
});
// ----------分页功能----------
function handleSizeChange(size) {
  console.log(size, 'size');
  pageSetting.value.page_size = size;
  console.log(pageSetting.value.page_size);
  userList.value = [];
  loadUserList();
}
function handleCurrentChange(page) {
  console.log(page, 'page');
  pageSetting.value.page_num = page;
  console.log(pageSetting.value.page_num);
  userList.value = [];
  loadUserList();
}
// ----------分页功能----------

// ----------内容表格，处理用户类型----------
const getRoleLabel = (roleId) => {
  if (roleId == 0) return "管理员";
  if (roleId == 1) return "老师";
  if (roleId == 2) return "评委";
  if (roleId == 3) return "观众";
};
// ----------内容表格，处理用户类型----------

// ----------获取用户数据列表----------
// 存放所有用户数据列表
const userList = ref([]);
// 获取所有用户数据列表
async function loadUserList() {
  userList.value = [];
  try {
    console.log(pageSetting.value)
    const response = await GetUserList(pageSetting.value);
    if (response.data) {
      userList.value.push(...response.data.pageList);
      pageSetting.value.page_num = response.data.pageNum;
      pageSetting.value.page_size = response.data.pageSize;
      pageSetting.value.total = response.data.total;
      console.log("获取数据列表成功", userList.value);
    }
  } catch (error) {
    console.error("获取数据列表失败", error);
  }
}

// 获取管理员列表
async function getAdmin() {
  try {
    pageSetting.value.roleId = 0;
    const res = await GetRoleList(pageSetting.value);
    userList.value = res.data.pageList;
    pageSetting.value.page_num = res.data.pageNum;
    pageSetting.value.page_size = res.data.pageSize;
    pageSetting.value.total = res.data.total;
  } catch (error) {
    console.log("获取失败", error)
  }
}

// 获取老师列表
async function getTeacher() {
  try {
    pageSetting.value.roleId = 1;
    const res = await GetRoleList(pageSetting.value);
    userList.value = res.data.pageList;
    pageSetting.value.page_num = res.data.pageNum;
    pageSetting.value.page_size = res.data.pageSize;
    pageSetting.value.total = res.data.total;
  } catch (error) {
    console.log("获取失败", error)
  }
}

// 获取评委列表
async function getJudge() {
  try {
    pageSetting.value.roleId = 2;
    const res = await GetRoleList(pageSetting.value);
    userList.value = res.data.pageList;
    pageSetting.value.page_num = res.data.pageNum;
    pageSetting.value.page_size = res.data.pageSize;
    pageSetting.value.total = res.data.total;
  } catch (error) {
    console.log("获取失败", error)
  }
}

// 获取观众列表
async function getAudience() {
  try {
    pageSetting.value.roleId = 3;
    const res = await GetRoleList(pageSetting.value);
    userList.value = res.data.pageList;
    pageSetting.value.page_num = res.data.pageNum;
    pageSetting.value.page_size = res.data.pageSize;
    pageSetting.value.total = res.data.total;
  } catch (error) {
    console.log("获取失败", error)
  }
}
// ----------获取用户数据列表----------

// ----------搜索功能----------
// 存放搜索的值
const searchVal = ref("");
// 搜索功能
async function searchById() {
  try {
    if (searchVal.value == null || searchVal.value == "") {
      GetUserById(pageSetting.value);
    } else {
      const v = {
        search: searchVal.value,
        page: pageSetting.value
      };
      userList.value = [];
      const response = await GetUserById(v);
      userList.value.push(...response.data);
      console.log("搜索成功", response);
    }
  } catch (error) {
    console.log("搜索错误", error)
  }
}
const searchByName = async () => {
  if (searchVal.value == null || searchVal.value == "") {
    ElMessage({
      message: "请输入搜索内容",
      type: "warning",
      duration: 1000,
    });
    return
  } else {
    const v = {
      search: searchVal.value,
      page: pageSetting.value
    };
    userList.value = [];
    const response = await GetUserByName(v);
    if (response.data.length == 0) {
      ElMessage({
        message: "未找到相关用户",
        type: "error",
      });
    } else {
      userList.value.push(...response.data);
    }
    console.log("搜索成功", response);
  }
}
// ----------搜索功能----------

// ----------删除功能----------
async function del(row) {
  const id = row.userId;
  ElMessageBox.confirm(
    `将删除用户${row.username}，是否继续？`,
    'Warning',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      try {
        await DeleteUserList(id);
        userList.value = [];
        await loadUserList();
        ElMessage({
          message: "删除成功",
          type: "success",
          ...messageConfig,
        });
        console.log("删除成功");
      } catch (error) {
        console.log("删除失败", error)
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}
// ----------删除功能----------

// ----------弹窗选项----------
// 用户类型，显示用户类型名称
const roleIdOptions = [
  {
    id: '0',
    name: '管理员'
  },
  {
    id: '1',
    name: '老师'
  },
  {
    id: '2',
    name: '评委'
  },
  {
    id: '3',
    name: '观众'
  }
];

const collegeOptions = [
  {
    id: "1",
    college: "智能制造学院"
  },
  {
    id: "2",
    college: "人文学院"
  },
  {
    id: "3",
    college: "设计学院"
  },
  {
    id: "4",
    college: "烹饪学院"
  },
  {
    id: "5",
    college: "酒店旅游与管理学院"
  },
];

// ----------弹窗选项----------

// ----------弹窗功能----------
// 控制弹窗是否显示
const dialogVisible = ref(false);
const edit = ref(false);
const add = ref(false);
// 弹窗的标题名称
const editFormTitle = ref("");

// 弹窗的数据变量
const editFormData = ref({
  userId: "",
  roleId: "",
  profilePath: "http://api.saike.qqwj.live/public/get-image?imagePath=386635483e5e4f2c9ed7a8b7d0997d7e.png",
  nickName: "",
  username: "",
  academy: "",
  phone: "",
  synopsis: "",
  password: 123456,
})

// 控制添加弹窗
const createUser = () => {
  editFormTitle.value = "创建用户";
  editFormData.value.synopsis = "这个人很懒，没有留下简介~~~"
  dialogVisible.value = true;
  add.value = true;
};

// 编辑弹窗数据
const editDialog = (rowData) => {
  editFormTitle.value = "编辑用户"
  editFormData.value = {
    userId: rowData.userId,
    roleId: rowData.roleId,
    profilePath: rowData.profilePath,
    nickName: rowData.nickName,
    username: rowData.username,
    academy: rowData.academy,
    phone: rowData.phone,
    synopsis: rowData.synopsis,
  }
  if (rowData.roleId == 0) { editFormData.value.roleId = "管理员" }
  if (rowData.roleId == 1) { editFormData.value.roleId = "老师" }
  if (rowData.roleId == 2) { editFormData.value.roleId = "评委" }
  if (rowData.roleId == 3) { editFormData.value.roleId = "观众" }
  dialogVisible.value = true;
  edit.value = true
}

// 处理添加或编辑窗格的”确认“按钮
async function handleConfirm() {
  try {
    if (edit.value) {
      if (editFormData.value.roleId == "管理员") { editFormData.value.roleId = 0 }
      if (editFormData.value.roleId == "老师") { editFormData.value.roleId = 1 }
      if (editFormData.value.roleId == "评委") { editFormData.value.roleId = 2 }
      if (editFormData.value.roleId == "观众") { editFormData.value.roleId = 3 }
      console.log("编辑成功", editFormData.value);
      await UpdateUserList(editFormData.value);
      edit.value = false;
    } else if (add.value) {
      console.log("添加成功", editFormData.value);
      await AddUserList(editFormData.value);
      add.value = false;
      handleBeforeClose()
    }
  } catch (error) {
    console.error("失败", error)
  }
  dialogVisible.value = false;
  userList.value = [];
  await loadUserList();
}

// 处理窗格的“取消”按钮
function handleBeforeClose() {
  editFormData.value = {
    userId: "",
    roleId: "",
    profilePath: "http://api.saike.qqwj.live/public/get-image?imagePath=386635483e5e4f2c9ed7a8b7d0997d7e.png",
    nickName: "",
    username: "",
    academy: "",
    phone: "",
    synopsis: "",
  password: 123456,

  };
  edit.value = false;
  add.value = false;
  dialogVisible.value = false
}
// ----------弹窗功能----------

// ----------重置密码----------
async function resetPassword(userData) {
  ElMessageBox.confirm(
    `将重置用户${userData.username}密码，是否继续？`,
    'Warning',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {

      userData.password = 123456;
      await UpdateUserPassword(userData);
      loadUserList();
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消',
      })
    })
}
// ----------重置密码----------

onMounted(() => {
  loadUserList();
});
</script>